<template>
	<view class="container">
		<loading v-if="isLoading" :height="windowHeight - 85"></loading>
		<view class="main" v-else>
			<!-- 导航栏 -->
			<customNavbar :scrollTop="scrollTop"></customNavbar>
			<!-- 轮播图 -->
			<customBanner :list="bannerList"></customBanner>
			<!-- 金刚区 -->
			<customDistrict></customDistrict>
			<!-- 拼团入口 -->
			<groupBuying></groupBuying>
			<!-- 视频 -->
			<customVideo></customVideo>
			<!-- 热卖 -->
			<hotSale></hotSale>
			<!-- 品牌 -->
			<customBrand></customBrand>
			<!-- 商品列表 -->
			<productList :list="productLists" :loadmoreStatus="loadmoreStatus"></productList>
		</view>
		<view class="safe-area-inset-bottom"></view>
		<!-- 首页已登录弹框 -->
		<customPopup ref="customPopupLogin">
			<template #header>
				<view class="coupon">
					<view class="li u-flex-between">
						<view class="li-left u-flex">
							<view class="left-content">
								<span class="num">9</span>
								<span class="unit">折</span>
							</view>
							<span class="text">折扣券</span>
						</view>
						<view class="li-right">品类使用优惠券</view>
					</view>
					<view class="li u-flex-between">
						<view class="li-left u-flex">
							<view class="left-content">
								<span class="unit">￥</span>
								<span class="num">20.8</span>
								<span class="unit">元</span>
							</view>
							<span class="text">直减券</span>
						</view>
						<view class="li-right">新用户直减券</view>
					</view>
				</view>
			</template>
			<template #content>
				<view class="content">
					<zero-lazy-load :borderRadius="6" :height="660" imgMode='aspectFill'
						image="https://qn.mtj.cdydsy.com/uploads/spread/20250421/image/10facdf1d2d30a0061c03b1b3f897de2.png"></zero-lazy-load>
				</view>
			</template>
			<template #footer>
				<view class="footer u-flex-center">
					<uni-icons type="closeempty" size="22" color="#FFFFFF"
						@click="customPopupLogin.close()"></uni-icons>
				</view>
			</template>
		</customPopup>
		<!-- 首页未登录弹框 -->
		<customPopup ref="customPopupNotLogin">
			<template #content>
				<view class="content" @click="toLogin">
					<zero-lazy-load class="image" :borderRadius="6" :height="660" imgMode='aspectFill'
						image="https://qn.mtj.cdydsy.com/uploads/spread/20241209/image/f45e7fd32c0b60e3f96bdc18158a4fa6.png"></zero-lazy-load>
				</view>
			</template>
			<template #footer>
				<view class="footer u-flex-center">
					<uni-icons type="closeempty" size="22" color="#FFFFFF"
						@click="customPopupNotLogin.close()"></uni-icons>
				</view>
			</template>
		</customPopup>
		<tabbar :current="0"></tabbar>
	</view>
</template>

<script setup>
	import customNavbar from './components/custom-navbar.vue'
	import customBanner from './components/custom-banner.vue'
	import customDistrict from './components/custom-district.vue'
	import customVideo from './components/custom-video.vue'
	import groupBuying from './components/group-buying.vue'
	import hotSale from './components/hot-sale.vue'
	import customBrand from './components/custom-brand.vue'
	import productList from './components/product-list.vue'
	import customPopup from './components/custom-popup.vue'
	import { apiGetProductList } from '@/api/product.js'
	import { onPageScroll, onReachBottom, onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
	import { ref, computed, watch, nextTick } from 'vue'
	import { navigateTo } from '@/utils/router.js'
	import useUserStore from '@/store/modules/user.js'
	import useIndexStore from '@/store/modules/index.js'
	import eventBus from '@/utils/eventBus.js'
	import { waitForAppLaunch } from '@/utils/common.js'

	onLoad(async () => {
		// #ifndef MP-WEIXIN
		uni.hideTabBar();
		// #endif
		await waitForAppLaunch() //等待初始化请求完成之后
		getData()
	})

	const { windowHeight } = wx.getWindowInfo()
	const userStore = useUserStore()
	const indexStore = useIndexStore()
	const isLoading = ref(true)
	const customPopupLogin = ref(null)
	const customPopupNotLogin = ref(null)
	const isLogin = computed(() => Boolean(userStore.token));

	// 开启已登录弹框
	const openChildPopupLogin = () => {
		customPopupLogin.value.open()
	};

	// 开启未登录弹框
	const openChildPopupNotLogin = () => {
		customPopupNotLogin.value.open()
	};

	const bannerList = [{
			image: "https://qn.mtj.cdydsy.com/uploads/spread/20250318/image/416a1a923139c5a47ad4d8816f2483b1.jpg"
		},
		{
			image: "https://qn.mtj.cdydsy.com/uploads/spread/20250318/image/416a1a923139c5a47ad4d8816f2483b1.jpg"
		},
		{
			image: "https://qn.mtj.cdydsy.com/uploads/spread/20250318/image/416a1a923139c5a47ad4d8816f2483b1.jpg"
		}
	]

	const scrollTop = ref(0)
	const productLists = ref([])
	const params = {
		page: 1,
		page_size: 10
	}
	const loadmoreStatus = ref(2);
	const noData = ref(false)

	// 获取商品列表
	const getProductList = async () => {
		try {
			const { data } = await apiGetProductList({
				page: params.page,
				page_size: params.page_size
			})
			productLists.value = [...productLists.value, ...data.data]
			if (params.page_size > data.data.length) {
				noData.value = true
				loadmoreStatus.value = 3
			}
			return Promise.resolve('ok');
		} finally {
			isLoading.value = false
		}
	}

	// 监听滚动事件
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop
	})

	// 触底加载更多
	onReachBottom(() => {
		if (noData.value || !productLists.value.length) return;
		loadmoreStatus.value = 1
		params.page++
		getProductList()
	})

	const tabChange = (index) => {
		console.log(index, 'index');
	}

	// 登录-未登录弹框
	const handleMountedLogic = () => {
		if (isLogin.value) {
			// 开启登录之后的弹框
			openChildPopupLogin();
		} else {
			// 开启未登录之后的弹框
			openChildPopupNotLogin();
		}
	};

	// 去登录
	const toLogin = () => {
		navigateTo('/pages/login/index')
		customPopupNotLogin.value.close()
	}

	const getData = async (type = 1) => {
		try {
			// 获取首页信息
			await indexStore.getIndexData();
			// 获取商品列表
			await getProductList();
		} finally {
			uni.stopPullDownRefresh()
			if (type === 1) {
				nextTick(() => {
					// 无论前面的操作是否出错，都会执行 handleMountedLogic 方法
					handleMountedLogic();
				})
			}
		}
	};

	// 下拉刷新
	onPullDownRefresh(() => {
		productLists.value = [];
		params.page = 1;
		loadmoreStatus.value = 2
		noData.value = false
		getData(2);
	})

	// 监听登录成功事件
	eventBus.value.on('loginSuccess', () => {
		productLists.value = [];
		params.page = 1;
		loadmoreStatus.value = 2
		noData.value = false
		getData();
	});
</script>

<style lang="scss" scoped>
	.container {
		.coupon {
			.li {
				width: 440rpx;
				padding: 0 10rpx;
				border-radius: 4rpx;
				line-height: 1;
				height: 72rpx;
				background: url() center top / 100% auto no-repeat;
				margin-top: 20rpx;

				.li-left {
					width: 180rpx;

					.left-content {
						flex: 1;
						text-align: center;

						.num {
							font-family: Source Han Sans CN, Source Han Sans CN;
							font-weight: 500;
							font-size: $font-size-32;
							color: $base-price-color;
						}

						.unit {
							font-family: Source Han Sans CN, Source Han Sans CN;
							font-weight: 400;
							font-size: $font-size-20;
							color: $base-price-color;
						}
					}

					.text {
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 400;
						font-size: $font-size-24;
						color: $base-price-color;
					}
				}

				.li-right {
					font-family: Source Han Sans CN, Source Han Sans CN;
					font-weight: 400;
					font-size: $font-size-26;
					color: $base-color;
					flex: 1;
					text-align: center;
				}
			}
		}

		.content {
			width: 440rpx;
			margin-top: 20rpx;
		}

		.footer {
			width: 56rpx;
			height: 56rpx;
			border-radius: 50%;
			border: 1px solid $base-color-white;
			margin: 60rpx auto 0;
		}
	}
</style>